package com.eaero.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eaero.CommonResp;
import com.eaero.entity.TraceHandover;
import com.eaero.entity.TraceHandoverDetail;
import com.eaero.mapper.TraceHandoverDetailMapper;
import com.eaero.service.ITraceHandoverDetailService;
import com.eaero.service.ITraceHandoverService;
import com.eaero.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zb
 * @since 2023-03-14
 */
@Service
public class TraceHandoverDetailServiceImpl extends ServiceImpl<TraceHandoverDetailMapper, TraceHandoverDetail> implements ITraceHandoverDetailService {

    @Autowired
    private ITraceHandoverService traceHandoverService;

    /**
     * 查询交接班明细
     *
     * @param request
     * @return
     */
    @Override
    public CommonResp getHandoverDtlInfo(HandoverDtlRequest request) {
        if (Objects.isNull(request.getTsId()) && StrUtil.isBlank(request.getWarehouse()) &&
                StrUtil.isBlank(request.getHoDate()) && StrUtil.isBlank(request.getShift()) && StrUtil.isBlank(request.getStoresloc())) {
            return CommonResp.buildFailMsg("1", "交接班信息获取失败！");
        }

        LocalDateTime crtStartTime = null;
        LocalDateTime crtEndTime = null;
        if (StrUtil.isNotBlank(request.getHoDate())) {
            LocalDate crtDate = LocalDate.parse(request.getHoDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            crtStartTime = LocalDateTime.of(crtDate, LocalTime.MIN);
            crtEndTime = LocalDateTime.of(crtDate, LocalTime.MAX);
        }

        List<TraceHandoverDetail> traceHandoverDetails = getBaseMapper().selectList(Wrappers.<TraceHandoverDetail>lambdaQuery()
                .eq(!Objects.isNull(request.getTsId()), TraceHandoverDetail::getTsId, request.getTsId())
                .eq(StrUtil.isNotBlank(request.getWarehouse()), TraceHandoverDetail::getWarehouse, request.getWarehouse())
                .ge(ObjectUtil.isNotEmpty(crtStartTime), TraceHandoverDetail::getCreateTime, crtStartTime)
                .le(ObjectUtil.isNotEmpty(crtEndTime), TraceHandoverDetail::getCreateTime, crtEndTime)
                .eq(StrUtil.isNotBlank(request.getShift()), TraceHandoverDetail::getShift, request.getShift())
                .eq(StrUtil.isNotBlank(request.getStoresloc()), TraceHandoverDetail::getStoresloc, request.getStoresloc())
                .orderByDesc(TraceHandoverDetail::getCreateTime)
        );
        return CommonResp.buildSucsDataListMsg(traceHandoverDetails, "数据获取成功！");
    }

    /**
     * 查询交接班明细定位
     *
     * @param request
     * @return
     */
    @Override
    public CommonResp getHandoverDtlLoc(HandoverDtlLocRequest request) {
        if (Objects.isNull(request.getTsId()) && StrUtil.isBlank(request.getWarehouse()) &&
                StrUtil.isBlank(request.getHoDate()) && StrUtil.isBlank(request.getShift())) {
            return CommonResp.buildFailMsg("1", "交接班信息获取失败！");
        }

        List<TraceHandoverDetail> traceHandoverDetails = getBaseMapper().selectList(Wrappers.<TraceHandoverDetail>lambdaQuery()
                .eq(!Objects.isNull(request.getTsId()), TraceHandoverDetail::getTsId, request.getTsId())
                .eq(StrUtil.isNotBlank(request.getWarehouse()), TraceHandoverDetail::getWarehouse, request.getWarehouse())
                .like(StrUtil.isNotBlank(request.getHoDate()), TraceHandoverDetail::getCreateTime, request.getHoDate())
                .eq(StrUtil.isNotBlank(request.getShift()), TraceHandoverDetail::getShift, request.getShift())
                .orderByDesc(TraceHandoverDetail::getCreateTime));

        List<HandoverDelLocVo> res = new ArrayList<>();
        Map<Integer, List<TraceHandoverDetail>> collect = traceHandoverDetails.stream().collect(Collectors.groupingBy(TraceHandoverDetail::getTsdId));
        for (Map.Entry<Integer, List<TraceHandoverDetail>> integerListEntry : collect.entrySet()) {
            HandoverDelLocVo handoverDelLocVo = new HandoverDelLocVo();
            try {
                TraceHandoverDetail traceHandoverDetail = integerListEntry.getValue().get(0);
                BeanUtil.copyProperties(traceHandoverDetail, handoverDelLocVo);
                res.add(handoverDelLocVo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return CommonResp.buildSucsDataListMsg(res, "数据获取成功！");
    }


    /**
     * 接班
     *
     * @param request
     * @return
     */
    @Override
    public CommonResp doHandover(DoHandoverRequest request) {
        List<List<TraceHandoverDetail>> traceHandoverDetails = new ArrayList<>();
        List<TraceHandover> traceHandovers = new ArrayList<>();
        for (DoHandoverItem doHandoverItem : request.getDoHandoverDtl()) {
            traceHandoverDetails.add(getBaseMapper().selectList(Wrappers.<TraceHandoverDetail>lambdaQuery()
                    .eq(TraceHandoverDetail::getTsdId, doHandoverItem.getTsdId())

            ));
            if (!NumberUtil.isInteger(doHandoverItem.getWhseCheck())) {
                return CommonResp.buildFailMsg("1", "盘点数量需为正整数");
            }
        }
        int tsid = 0;
        if (!Objects.isNull(traceHandoverDetails.get(0))) {
            tsid = traceHandoverDetails.get(0).get(0).getTsId();
        }

        for (List<TraceHandoverDetail> traceHandoverDetail : traceHandoverDetails) {
            for (TraceHandoverDetail detail : traceHandoverDetail) {
                if (detail.getTsId() != tsid) {
                    return CommonResp.buildFailMsg("1", "一次提交的交班单明细需属于同一张交班单");
                }
                TraceHandover byId = traceHandoverService.getById(detail.getTsId());
                traceHandovers.add(byId);
                if (!StrUtil.equals("交班", byId.getStatus()) && !StrUtil.equals("接班", byId.getStatus())) {
                    return CommonResp.buildFailMsg("1", "仅交班状态、接班状态可以进行接班操作");
                }
            }
        }


        for (TraceHandover traceHandover : traceHandovers) {
            traceHandover.setToRemark(request.getToRemark());
            traceHandover.setStatus("关闭");
        }

        for (DoHandoverItem doHandoverItem : request.getDoHandoverDtl()) {
            TraceHandoverDetail traceHandoverDetail = new TraceHandoverDetail();
            traceHandoverDetail.setTsdId(Integer.valueOf(doHandoverItem.getTsdId()));
            traceHandoverDetail.setRemark(doHandoverItem.getRemark());
            traceHandoverDetail.setIsHandingOf("1");
            traceHandoverDetail.setWhseCheck(Integer.valueOf(doHandoverItem.getWhseCheck()));
            traceHandoverDetail.setToRemark(request.getToRemark());
            update(traceHandoverDetail, Wrappers.<TraceHandoverDetail>lambdaQuery()
                    .eq(TraceHandoverDetail::getTsdId, doHandoverItem.getTsdId())
            );
        }

        traceHandovers.forEach(traceHandover -> {
            Long count = getBaseMapper().selectCount(Wrappers.<TraceHandoverDetail>lambdaQuery()
                    .eq(TraceHandoverDetail::getIsHandingOf, "0")
                    .eq(TraceHandoverDetail::getTsId, traceHandover.getTsId()));
            if (count == 0) {
                traceHandover.setToUser(request.getUserCode());
                traceHandoverService.updateById(traceHandover);
            }
        });

        return CommonResp.buildSucsDataListMsg(null, "接班成功！");
    }
}
